#if !defined(ANY_ELEMENT_WITHIN_RANGE_H)
#define ANY_ELEMENT_WITHIN_RANGE_H

/////////////////////////////////////////////////////////////////////////////
// any_element_within_range.h
//
//	returns whether any elements in two containers are at or within a specified range
// 	of each other
// E.g. (1,2,3,4,5) and (-22,-18,7,23,50) have 5 and 7 within a range of 2

namespace leo_algo
{

template<	typename T, template< typename T> class CONT1,
			typename U, template< typename U> class CONT2,
			typename R>
bool any_element_within_range(const CONT1<T>& data1, const CONT2<U>& data2, R range)
{
	typename CONT1<T>::const_iterator iter1	= data1.begin();
	typename CONT1<T>::const_iterator end1		= data1.end();;
	typename CONT2<T>::const_iterator iter2	= data2.begin();
	typename CONT2<T>::const_iterator end2		= data2.end();;
	if (iter1 == end1)
		return false;

	while (iter2 != end2)
	{
		if (*iter2 < *iter1)
		{
			if (*iter1 - *iter2 <= range)
				return true;

			// iterate through inner loop while iter2 < iter1
			++iter2;
			continue;
		}

		if (*iter2 - *iter1 <= range)
			return true;

		// iterate through outer loop while iter2 < iter1
		++iter1;
		if (iter1 == end1)
			return false;
		continue;
	}
	return false;
}


template<	typename T, template< typename T> class CONT1,
			typename U, template< typename U> class CONT2,
			typename R>
bool any_element_within_range(const CONT1<T>& data1, const CONT2<U>& data2, R range, 
								T& ret1, U& ret2)
{
	typename CONT1<T>::const_iterator iter1	= data1.begin();
	typename CONT1<T>::const_iterator end1		= data1.end();;
	typename CONT2<T>::const_iterator iter2	= data2.begin();
	typename CONT2<T>::const_iterator end2		= data2.end();;


	if (iter1 == end1)
		return false;

	while (iter2 != end2)
	{
		if (*iter2 < *iter1)
		{
			if (*iter1 - *iter2 <= range)
			{
				ret1 = *iter1;
				ret2 = *iter2;
				return true;
			}

			// iterate through inner loop while iter2 < iter1
			++iter2;
			continue;
		}

		if (*iter2 - *iter1 <= range)
		{
			ret1 = *iter1;
			ret2 = *iter2;
			return true;
		}

		// iterate through outer loop while iter2 < iter1
		++iter1;
		if (iter1 == end1)
			return false;
		continue;
	}
	return false;
}
}
#endif
